#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QFileDialog>
#include <QComboBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , model(new QStandardItemModel)
{
    ui->setupUi(this);
    ui->setupUi(this);

    this->setWindowIcon(QIcon(":/logo.png"));
    this->setWindowTitle("大工新时代成就统计与查询系统");

    ui->resultView->setModel(model);
    ui->resultView->horizontalHeader()->setSectionsClickable(true); // 允许点击表头
    ui->resultView->horizontalHeader()->setSortIndicatorShown(true); // 显示排序指示器
    ui->resultView->setSortingEnabled(true); // 启用排序功能
    // 添加表头
    model->setColumnCount(5); // 有5列: 年份, 技术名称, 带头人/团队, 领域, 简介
    model->setHeaderData(0, Qt::Horizontal, QObject::tr("年份"));
    model->setHeaderData(1, Qt::Horizontal, QObject::tr("技术名称"));
    model->setHeaderData(2, Qt::Horizontal, QObject::tr("带头人/团队"));
    model->setHeaderData(3, Qt::Horizontal, QObject::tr("领域"));
    model->setHeaderData(4, Qt::Horizontal, QObject::tr("简介"));
    ui->resultView->setColumnWidth(0,50);
    ui->resultView->setColumnWidth(1,150);
    ui->resultView->setColumnWidth(2,150);
    ui->resultView->setColumnWidth(3,150);
    ui->resultView->setColumnWidth(4,300);

    // 初始化饼状图视图
    chartView = new QChartView(this);
    chartView->setRenderHint(QPainter::Antialiasing);

    // 创建一个对话框用于显示饼状图
    chartDialog = new QDialog(this);
    chartDialog->setWindowTitle(tr("领域分布饼状图"));
    QVBoxLayout *layout = new QVBoxLayout(chartDialog);
    layout->addWidget(chartView);
    chartDialog->setLayout(layout);


    connect(ui->addButton, &QPushButton::clicked, this, &MainWindow::on_addButton_clicked);
    connect(ui->importButton, &QPushButton::clicked, this, &MainWindow::on_importButton_clicked);
    connect(ui->exportButton, &QPushButton::clicked, this, &MainWindow::on_exportButton_clicked);
    connect(ui->drawChartButton, &QPushButton::clicked, this, &MainWindow::on_drawChartButton_clicked);
    connect(ui->queryButton, &QPushButton::clicked, this, &MainWindow::on_queryButton_clicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_addButton_clicked()
{
    // 创建一个对话框
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle(tr("添加新成就"));

    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout(dialog);

    // 创建输入字段
    QLineEdit *yearEdit = new QLineEdit(dialog);
    QLineEdit *techNameEdit = new QLineEdit(dialog);
    QLineEdit *leaderEdit = new QLineEdit(dialog);
    QLineEdit *fieldEdit = new QLineEdit(dialog);
    QLineEdit *descriptionEdit = new QLineEdit(dialog);

    // 添加字段到表单布局
    formLayout->addRow(tr("年份"), yearEdit);
    formLayout->addRow(tr("技术名称"), techNameEdit);
    formLayout->addRow(tr("带头人/团队"), leaderEdit);
    formLayout->addRow(tr("领域"), fieldEdit);
    formLayout->addRow(tr("简介"), descriptionEdit);

    // 添加按钮
    QPushButton *okButton = new QPushButton(tr("确定"), dialog);
    QPushButton *cancelButton = new QPushButton(tr("取消"), dialog);
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);
    formLayout->addRow(buttonLayout);

    // 连接按钮信号
    connect(okButton, &QPushButton::clicked, dialog, [dialog, yearEdit, techNameEdit, leaderEdit, fieldEdit, descriptionEdit, this]() {
        // 获取用户输入
        QString year = yearEdit->text();
        QString techName = techNameEdit->text();
        QString leader = leaderEdit->text();
        QString field = fieldEdit->text();
        QString description = descriptionEdit->text();

        // 检查输入是否为空
        if (year.isEmpty() || techName.isEmpty() || leader.isEmpty() || field.isEmpty() || description.isEmpty()) {
            QMessageBox::warning(dialog, tr("警告"), tr("所有字段都必须填写！"));
            return;
        }

        // 添加到模型
        int row = model->rowCount();
        model->insertRow(row);
        model->setData(model->index(row, 0), year);
        model->setData(model->index(row, 1), techName);
        model->setData(model->index(row, 2), leader);
        model->setData(model->index(row, 3), field);
        model->setData(model->index(row, 4), description);

        // 关闭对话框
        dialog->accept();
    });

    connect(cancelButton, &QPushButton::clicked, dialog, &QDialog::reject);

    // 显示对话框
    dialog->exec();
}


void MainWindow::on_importButton_clicked()
{
    // 弹出文件选择对话框，让用户选择 Excel 文件
    QString filePath = QFileDialog::getOpenFileName(this, tr("选择 Excel 文件"), "", tr("Excel 文件 (*.xlsx)"));
    if (filePath.isEmpty()) {
        // 如果用户取消选择，直接返回
        return;
    }

    // 打开 Excel 文件
    QXlsx::Document xlsxR(filePath);

    // 检查文件是否加载成功
    if (xlsxR.load()) {
        qDebug() << "[debug] success to load xlsx file.";
    }

    // 清空当前模型
    model->removeRows(0, model->rowCount());


    // 遍历工作表内容
    int row = 2; // 从第 2 行开始，假设第 1 行是表头
    while (true) {
        QList<QStandardItem *> rowItems;
        bool rowIsEmpty = true;

        for (int col = 1; col <= 5; ++col) { // 只读取前 5 列
            QXlsx::Cell *cell = xlsxR.cellAt(row, col).get();
            QString cellValue;
            if (cell) {
                cellValue = cell->readValue().toString();
                if (!cellValue.isEmpty()) {
                    rowIsEmpty = false; // 如果单元格不为空，标记该行不为空
                }
            }
            QStandardItem *item = new QStandardItem(cellValue);
            rowItems.append(item);
        }

        // 如果该行为空，停止导入
        if (rowIsEmpty) {
            break;
        }

        // 添加一行到模型
        model->appendRow(rowItems);

        // 移动到下一行
        ++row;
    }

    // 更新视图
    ui->resultView->viewport()->update();
}


void MainWindow::on_exportButton_clicked()
{
    // 弹出文件保存对话框，让用户选择保存路径和文件名
    QString filePath = QFileDialog::getSaveFileName(this, tr("保存 Excel 文件"), "", tr("Excel 文件 (*.xlsx)"));
    if (filePath.isEmpty()) {
        // 如果用户取消选择，直接返回
        return;
    }

    // 确保文件名以 .xlsx 结尾
    if (!filePath.endsWith(".xlsx", Qt::CaseInsensitive)) {
        filePath += ".xlsx";
    }

    // 创建 Excel 文档
    QXlsx::Document xlsxW;

    // 添加一个工作表
    xlsxW.addSheet("Sheet1");

    // 获取当前工作表
    QXlsx::Worksheet *worksheet = xlsxW.currentWorksheet();

    // 获取表头
    QStringList headers = { "年份", "技术名称", "带头人/团队", "领域", "简介" };

    // 写入表头
    for (int col = 0; col < headers.size(); ++col) {
        xlsxW.write(1, col + 1, headers[col]); // 写入表头
    }

    // 获取模型数据
    int rowCount = model->rowCount();
    int columnCount = model->columnCount();

    // 写入数据
    for (int row = 0; row < rowCount; ++row) {
        for (int col = 0; col < columnCount; ++col) {
            QStandardItem *item = model->item(row, col);
            if (item) {
                xlsxW.write(row + 2, col + 1, item->text()); // 写入数据，从第 2 行开始
            }
        }
    }

    // 保存文件
    if (xlsxW.saveAs(filePath)) {
        QMessageBox::information(this, tr("成功"), tr("文件已成功导出到 %1").arg(filePath));
    } else {
        QMessageBox::critical(this, tr("错误"), tr("无法保存文件！"));
    }
}


void MainWindow::on_drawChartButton_clicked()
{
    // 清空之前的饼状图
    chartView->chart()->removeAllSeries();

    // 创建一个新的饼状图系列
    QPieSeries *series = new QPieSeries();

    // 从模型中获取“领域”字段的数据
    int rowCount = model->rowCount();
    QMap<QString, int> fieldCounts;

    for (int row = 0; row < rowCount; ++row) {
        QStandardItem *item = model->item(row, 3); // “领域”字段在第 4 列
        if (item) {
            QString field = item->text();
            fieldCounts[field]++;
        }
    }

    // 添加数据到饼状图系列
    for (auto it = fieldCounts.cbegin(); it != fieldCounts.cend(); ++it) {
        QPieSlice *slice = series->append(it.key(), it.value());
        slice->setLabel(it.key() + " (" + QString::number(it.value()) + ")");
    }

    // 设置饼状图的标题
    QChart *chart = new QChart();
    chart->setTitle("领域分布");
    chart->addSeries(series);

    // 设置饼状图的样式
    series->setLabelsVisible(true);
    series->setLabelsPosition(QPieSlice::LabelInsideHorizontal);

    // 为每个切片设置不同的颜色
    QList<QColor> colors = {
        QColor(255, 99, 132), // 红色
        QColor(54, 162, 235), // 蓝色
        QColor(255, 206, 86), // 黄色
        QColor(75, 192, 192), // 绿色
        QColor(153, 102, 255), // 紫色
        QColor(255, 159, 64)  // 橙色
    };

    int colorIndex = 0;
    for (auto slice : series->slices()) {
        slice->setColor(colors[colorIndex % colors.size()]);
        colorIndex++;
    }

    // 设置饼状图的视图
    chartView->setChart(chart);

    // 显示对话框
    chartDialog->show();

    chartDialog->resize(600,400);
}


void MainWindow::on_queryButton_clicked()
{
    // 创建查询对话框
    QDialog *queryDialog = new QDialog(this);
    queryDialog->setWindowTitle(tr("查询"));
    QVBoxLayout *queryLayout = new QVBoxLayout(queryDialog);

    // 添加查询选项
    QLabel *label = new QLabel(tr("查询内容："));
    queryLayout->addWidget(label);

    QComboBox *queryComboBox = new QComboBox;
    queryComboBox->addItem(tr("年份"));
    queryComboBox->addItem(tr("技术名称"));
    queryComboBox->addItem(tr("带头人/团队"));
    queryComboBox->addItem(tr("领域"));
    queryComboBox->addItem(tr("简介"));
    queryLayout->addWidget(queryComboBox);

    QLineEdit *queryLineEdit = new QLineEdit;
    queryLayout->addWidget(queryLineEdit);

    QPushButton *queryButton = new QPushButton(tr("查询"));
    queryLayout->addWidget(queryButton);

    // 连接查询按钮的点击信号
    connect(queryButton, &QPushButton::clicked, this, [this, queryComboBox, queryLineEdit, queryDialog]() {
        QString queryColumn = queryComboBox->currentText();
        QString queryText = queryLineEdit->text();
        bool found = false;//是否查询到
        // 重置所有行的背景颜色
        for (int row = 0; row < model->rowCount(); ++row) {
            for (int col = 0; col < model->columnCount(); ++col) {
                QStandardItem *item = model->item(row, col);
                if (item) {
                    item->setBackground(QBrush(Qt::white)); // 设置默认背景颜色
                }
            }
        }

        // 查询
        for (int row = 0; row < model->rowCount(); ++row) {
            QStandardItem *item = nullptr;
            int colIndex = -1;

            if (queryColumn == tr("年份")) {
                colIndex = 0;
            } else if (queryColumn == tr("技术名称")) {
                colIndex = 1;
            } else if (queryColumn == tr("带头人/团队")) {
                colIndex = 2;
            } else if (queryColumn == tr("领域")) {
                colIndex = 3;
            } else if (queryColumn == tr("简介")) {
                colIndex = 4;
            }

            if (colIndex != -1) {
                item = model->item(row, colIndex);
            }

            if (item && item->text().contains(queryText, Qt::CaseInsensitive)) {
                // 如果匹配，高亮显示该行
                for (int col = 0; col < model->columnCount(); ++col) {
                    QStandardItem *cellItem = model->item(row, col);
                    if (cellItem) {
                        cellItem->setBackground(QBrush(Qt::yellow)); // 设置高亮背景颜色

                    }
                }
                found = true; // 设置标志变量为 true
            }
        }
        if (!found) {
            // 如果没有找到匹配的行，弹出提示框
            QMessageBox::information(this, tr("查询结果"), tr("未找到匹配的记录。"));
        }
        queryDialog->close();
    });

    queryDialog->setLayout(queryLayout);
    queryDialog->exec(); // 使用 exec() 以模态方式显示对话框
}

